import store from '@/store'
import { logout } from '@/store/actions/login'
import { message } from 'antd'
import axios from 'axios'
import history from './history'
import { getToken, hasToken } from './storage'

const instance = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0/',
  timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    if (hasToken) {
      config.headers.Authorization = 'Bearer ' + getToken()
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    if (error.response.status === 401) {
      // 当 error.response.status 等于401是说明token失效了
      // 提示消息
      message.error('登录信息过期', 2)
      // 清除token
      store.dispatch(logout())
      // 跳转到登录 history
      history.push('/login')
    }
    if (!error.response) {
      message.error('网络错误', 1)
    }
    return Promise.reject(error)
  }
)

export default instance
